package cn.com.fuhuitong.main.home.ui.fragment

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.entity.EmptyState
import cn.com.fuhuitong.main.base.ViewModeFragment
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.app.BASE_HTTP_URL
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.EmptyContent
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.WebConfig
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.ItemViewType
import cn.com.fuhuitong.main.home.adapter.CategoryListAdapter
import cn.com.fuhuitong.main.home.vm.CaseViewModel
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.tencent.smtt.sdk.TbsVideo
import kotlinx.android.synthetic.main.fragment_home_category.*

class HomeCategoryFragment : ViewModeFragment<CaseViewModel>() {

    companion object {
        private const val HOME_ICON_ID = "homeIconId"
        private const val TWO_HOME_ICON_ID = "twoHomeIconId"
        fun newInstance(homeIconId: Int, twoHomeIconId: Int): HomeCategoryFragment {
            val fragment = HomeCategoryFragment()
            fragment.arguments = Bundle().apply {
                putInt(HOME_ICON_ID, homeIconId)
                putInt(TWO_HOME_ICON_ID, twoHomeIconId)
            }
            return fragment
        }
    }

    private lateinit var mCategoryListAdapter: CategoryListAdapter

    private val mHomeIconId: Int
        get() = arguments?.getInt(HOME_ICON_ID) ?: 0

    private val mTwoHomeIconId: Int
        get() = arguments?.getInt(TWO_HOME_ICON_ID) ?: 0

    override fun viewModel(): CaseViewModel = ViewModelProvider(
        this, ViewModelProvider.AndroidViewModelFactory(BaseApplication.INSTANCE)
    ).get(CaseViewModel::class.java)

    override val layoutResId: Int
        get() = R.layout.fragment_home_category

    override fun initView() {

        this.initViewRecyclerAdapter(
            recycler_category_list, arrayOf(ItemViewType.CASE_LIST)
        )

        delegateAdapter.addAdapter(CategoryListAdapter(
            requireContext(), LinearLayoutHelper().apply {
                setDividerHeight(resources.getDimensionPixelSize(R.dimen.dp_10))
            }
        ).apply { mCategoryListAdapter = this })

        mCategoryListAdapter.setOnItemClickListener { view, i, caseEntity ->
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                .withSerializable(
                    AppConstance.BUNDLE_WEB_VIEW,
                    MainBean(type = WebConfig.UNKNOWN.apply {
                        desc = caseEntity.title
                    }, data = if (caseEntity.url.isNullOrEmpty()) caseEntity.content else caseEntity.url)
                )
                .navigation()
        }

        mCategoryListAdapter.setOnItemChildClickListener { view, i, caseEntity ->
            when (view.id) {
                R.id.text_case_list_video_play -> {
                    if (TbsVideo.canUseTbsPlayer(requireActivity())) {
                        TbsVideo.openVideo(
                            requireActivity(),
                            "$BASE_HTTP_URL${caseEntity.file}",
                            Bundle().apply {
                                putInt("screenMode", 102)
                            })
                    }
                }
            }
        }



        with(smartRefreshLayout) {
            setRefreshHeader(MaterialHeader(requireContext()))
            setRefreshFooter(ClassicsFooter(requireContext()))
        }
        smartRefreshLayout.setOnRefreshListener {
            smartRefreshLayout.finishRefresh(true)
            //viewModel.caseIndex(arguments?.getInt(TYPE) ?: 0)
            initData()
        }
        smartRefreshLayout.setOnLoadMoreListener {
            smartRefreshLayout.finishLoadMore(true)
            //viewModel.caseIndex(arguments?.getInt(TYPE) ?: 0)
            initData()
        }
    }

    override fun initData() {
        viewModel.caseIndex(mHomeIconId, mTwoHomeIconId)
    }

    override fun initViewMode() {
        viewModel.caseListDataLiveData.observe(viewLifecycleOwner, Observer { response ->


            val dataLength: Int = response.response?.data?.list?.size ?: 0

            smartRefreshLayout.isEnabled = dataLength != 0
            if (dataLength < 100) {
                smartRefreshLayout.finishLoadMoreWithNoMoreData()
            }

            when (response.status) {
                HttpResponseStatus.Status.START -> {
                    if (dataLength == 0) {
                        showLoadEmptyView()
                    }
                }
                HttpResponseStatus.Status.SUCCESS -> {
                    if (dataLength == 0) {
                        showNullEmptyView(EmptyContent("重新加载", "暂无数据"))
                    } else {
                        hideEmptyView()
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    if (dataLength == 0) {
                        showErrorEmptyView(EmptyContent("重新加载", response.statusTip))
                    }
                    toast(response.statusTip)
                }
            }

            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.list?.let {
                mCategoryListAdapter.setAddDataNew(it)
            }
        })
    }

    override fun onLoadingEmptyView(state: EmptyState) {
        super.onLoadingEmptyView(state)
        initData()
    }

}